<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关键字" prop="chengguoName">
        <el-input v-model="queryParams.chengguoName" placeholder="请输入检索关键字" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" v-hasPermi="['archive:zt:achievement:add']"
          @click="handleAdd">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" v-hasPermi="['archive:zt:achievement:edit']"
          :disabled="single" @click="handleUpdate">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" v-hasPermi="['archive:zt:achievement:remove']"
          :disabled="multiple" @click="handleDelete">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" v-hasPermi="['archive:zt:achievement:export']"
          @click="handleExport">成果导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-delete" v-hasPermi="['archive:zt:achievement:download']"
          :disabled="single" @click="handleDownload">成果下载
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-delete" v-hasPermi="['archive:zt:achievement:editState']"
          :disabled="multiple" @click="handleIssue(1)">发布
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-delete" v-hasPermi="['archive:zt:achievement:editState']"
          :disabled="multiple" @click="handleIssue(0)">撤销发布
        </el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="zhuantichengguoList" @selection-change="handleSelectionChange"
      :height="tableHeight">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" :index="table_index" width="55" align="center" prop="chengguoId" />
      <el-table-column label="专题成果名称" align="center" prop="chengguoName" />
      <el-table-column label="发布状态" align="center" prop="issueState">
        <template slot-scope="scope">
          {{ scope.row.issueState == '0' ? "未发布" : scope.row.issueState == '1' ? "已发布" : '' }}
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="unitName" />
      <el-table-column label="存放位置" align="center" prop="depositPath" />
      <el-table-column label="主编" align="center" prop="editorName" />
      <el-table-column label="出版方式" align="center" prop="publishType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.PUBLISH_TYPE" :value="scope.row.publishType" />
        </template>
      </el-table-column>
      <el-table-column label="出版社" align="center" prop="pressName" />
      <el-table-column label="出版时间" align="center" prop="publishTime" />
      <el-table-column label="副主编" align="center" prop="viceEditor" />
      <el-table-column label="历史顾问" align="center" prop="historyAdviser" />
      <el-table-column label="编辑人员" align="center" prop="editStaff" />
      <el-table-column label="总页数" align="center" prop="pageCount" />
      <el-table-column label="总字数" align="center" prop="woedCount" />
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.isShowButton" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button v-if="scope.row.isShowButton" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
          </el-button>
          <el-button type="text" icon="el-icon-document" @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改专题成果对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="45%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="专题名称" prop="chengguoName">
              <el-input v-model="form.chengguoName" placeholder="请输入专题名称" :disabled="isShowDetail" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单  位" prop="unitName">
              <el-input v-model="form.unitName" placeholder="请输入单位" :disabled="isShowDetail" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="出版方式" prop="publishType">
              <el-select v-model="form.publishType" placeholder="请选择出版方式" style="width: 100%;" :disabled="isShowDetail">
                <el-option v-for="dict in dict.type.PUBLISH_TYPE" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存放位置" prop="depositPath">
              <el-input v-model="form.depositPath" placeholder="请输入存放位置" :disabled="isShowDetail" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="主  编" prop="editorName">
              <el-input v-model="form.editorName" placeholder="请输入主编名称" :disabled="isShowDetail" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出版社" prop="pressName">
              <el-input v-model="form.pressName" placeholder="请输入出版社名称" :disabled="isShowDetail" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="出版时间" prop="publishTime">
              <el-date-picker v-model="form.publishTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择出版时间" style="width: 100%;" :disabled="isShowDetail"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="副主编" prop="viceEditor">
              <el-input v-model="form.viceEditor" placeholder="请输入副主编名称" :disabled="isShowDetail" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="历史顾问" prop="historyAdviser">
              <el-input v-model="form.historyAdviser" placeholder="请输入历史顾问名称" :disabled="isShowDetail" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="编辑人员" prop="editStaff">
              <el-input v-model="form.editStaff" placeholder="请输入编辑人员名称" :disabled="isShowDetail" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="总页数" prop="pageCount">
              <el-input v-model="form.pageCount" placeholder="请输入总页数" :disabled="isShowDetail" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总字数" prop="woedCount">
              <el-input v-model="form.woedCount" placeholder="请输入总字数 单位(个)" :disabled="isShowDetail" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isFbState">
          <el-col :span="12">
            <el-form-item label="密级" prop="mj">
              <el-select  v-model="form.mj" placeholder="请选择文件密级" style="width: 100%;" :disabled="isShowDetail">
                  <el-option v-for="(item, idx) in renyuanOptions" :key="idx" :label="item.dictLabel"
                    :value="item.dictValue"></el-option>
                </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" style="width: 100%" placeholder="请输入内容"
              :disabled="isShowDetail"></el-input>
          </el-form-item>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="附件">
              <div style="display:flex;">
                <div>

                  <el-upload multiple :action="uploadFileUrl" :file-list="fileList"
                    :on-success="handleUploadSuccess" :show-file-list="false" :headers="headers"
                    class="upload-file-uploader" ref="fileUpload" :data="uploadData">
                    <!-- 上传按钮 -->
                    　<el-button class="upload_btn" size="medium" type="primary" icon="el-icon-upload"
                      :disabled="isShowDetail">上传文件</el-button>
                  </el-upload>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <el-table :data="fileDataList" height="150px">
        <el-table-column label="文件名" align="center" prop="fileName" />
        <el-table-column label="文件大小" align="center" prop="fileSize" />
        <el-table-column label="文件路径" align="center" prop="filePath" />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-delete" @click="handleDeleteFile(scope.row)"
              :disabled="isShowDetail"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="fileTotal > 0" :total="fileTotal" :page.sync="fileParams.pageNum"
        :limit.sync="fileParams.pageSize" @pagination="getFileList" />

      <div slot="footer" class="dialog-footer" v-if="!isShowDetail">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addZhuanTiChengGuo,
  delZhuanTiChengGuo,
  editState,
  getFile,
  getZhuanTiChengGuo,
  listZhuanTiChengGuo,
  removeFile,
  updateZhuanTiChengGuo
} from "@/api/archive/bianyan/zhuantichengguo";

import { getToken } from "@/utils/auth";
import { getInfo } from "@/api/login";
import estimateTableHeight from "@/mixins/estimateTableHeight";
import { getDicts_archive } from '@/api/archive/dict/dictManageData'
import { fbstat } from "@/api/archive/fileCollection/offlinReception.js";
import {
  getdamjbyrymj
} from "@/api/archive/fileCollection/offlinReception.js";
export default {
  name: "app-container",
  archive_Dicts: ['PUBLISH_TYPE'],
  mixins: [estimateTableHeight], // 混入方法
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 是否允许修改和删除
      issueState: 0,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 专题成果表格数据
      zhuantichengguoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        chengguoName: null,
        unitName: null,
        createTime: null,
        CREATOR: null,
        creatorId: null,
        isDel: null,
        depositPath: null,
        editorName: null,
        publishType: null,
        pressName: null,
        publishTime: null,
        viceEditor: null,
        historyAdviser: null,
        editStaff: null,
        pageCount: null,
        woedCount: null,
        REMARK: null,
        issueState: null,

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        chengguoName: [
          { required: true, message: "专题名称不能为空", trigger: "blur" },
        ],
        unitName: [
          { required: true, message: "单位名称不能为空", trigger: "blur" },
        ],
        publishType: [
          { required: true, message: "请选择出版方式", trigger: "change" },
        ],
        mj:[
          { required: true, message: "请选择密级", trigger: "change" },
        ]

      },



      uploadFileUrl: process.env.VUE_APP_BASE_API + "/archive/zt/achievement/upload",
      fileList: [],
      // 设置上传的请求头部
      headers: { Authorization: "Bearer " + getToken() },
      fileData: [],
      fileDataList: [],
      uploadData: {
        id: ''
      },
      fileParams: {
        pageNum: 1,
        pageSize: 10
      },
      fileTotal: 0,
      isShowDetail: false,
      loginId: undefined,
      renyuanOptions: [],//密级下拉列表
      isFbState: false,
    };
  },
  created() {
    getInfo().then(res => {
      this.loginId = res.user.userId
    })
    this.getList();
    fbstat().then(res => {  //false=不是分保，true=是分保
      this.isFbState = res.data
      if (this.isFbState) {
        //密级下拉列表
        getDicts_archive("MJ").then(res => { //人员密级
          getdamjbyrymj().then(resdata => { //此接口没有返回dictLabel，需要组装接口
            var mjdata = [];
            for (var i in resdata.data) {
              for (var j in res.data) {
                if (resdata.data[i].daMj == res.data[j].dictValue) {
                  mjdata.push(res.data[j])
                }
              }
            }

            this.renyuanOptions = mjdata
          })
        })
      }
    })
  },
  methods: {
    /** 查询专题成果列表 */
    getList() {
      this.loading = true;
      listZhuanTiChengGuo(this.queryParams).then(response => {
        this.zhuantichengguoList = response.rows;
        for (let i = 0; i < this.zhuantichengguoList.length; i++) {
          if (this.zhuantichengguoList[i].creatorId == this.loginId) {
            this.zhuantichengguoList[i].isShowButton = true
          } else {
            this.zhuantichengguoList[i].isShowButton = false
          }
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        chengguoId: null,
        chengguoName: null,
        unitName: null,
        createTime: null,
        CREATOR: null,
        creatorId: null,
        isDel: null,
        depositPath: null,
        editorName: null,
        publishType: null,
        pressName: null,
        publishTime: null,
        viceEditor: null,
        historyAdviser: null,
        editStaff: null,
        pageCount: null,
        woedCount: null,
        REMARK: null,
        issueState: null,
        mj:null
      };
      this.fileMJ=undefined;
      this.resetForm("form");
    },
    /**序号*/
    table_index(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.chengguoId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.issueState = selection.map(item => item.issueState)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isShowDetail = false
      this.open = true;
      this.title = "添加专题成果";
      this.uploadData.id = '';
      this.fileDataList = []
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isShowDetail = false
      const chengguoId = row.chengguoId || this.ids
      this.uploadData.id = chengguoId.toString()
      this.fileParams.cgId = chengguoId.toString()
      this.getFileList()
      if (this.issueState == 1 || row.issueState == 1) {
        this.$message.warning("已发布,不允许修改,请先撤销发布!");
        return false;
      }
      getZhuanTiChengGuo(chengguoId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改专题成果";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.chengguoId != null) {
            this.form.ztcgFiles = this.fileDataList
            updateZhuanTiChengGuo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.ztcgFiles = this.fileDataList
            addZhuanTiChengGuo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const chengguoIds = row.chengguoId || this.ids;
      if (row.issueState == 1 || this.issueState == 1) {
        this.$message.warning("已发布,不允许删除,请先撤销发布!");
        return false;
      }
      this.$modal.confirm('是否确认删除所选数据项？').then(function () {
        return delZhuanTiChengGuo(chengguoIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('archive/zt/achievement/export', {
        ...this.queryParams,
        chengguoIds: this.ids.toString()
      }, `${new Date().getTime()}.xlsx`)
    },
    /** 成果下载按钮操作 */
    handleDownload(row) {
      const id = row.chengguoId || this.ids;
      const chengguoIds = id.toString()
      this.download('archive/zt/achievement/download', {
        ids: id.toString()
      }, `pack_${new Date().getTime()}.zip`)
    },

    /** 发布和撤销发布按钮 */
    handleIssue(st) {
      const chengguoIds = this.ids;
      let data = {
        ids: chengguoIds,
        state: st
      }
      if (st == 0) {
        editState(data).then(response => {
          this.getList();
          this.$modal.msgSuccess("撤销成功");
        });
      } else {
        editState(data).then(response => {
          this.getList();
          this.$modal.msgSuccess("发布成功");
        });
      }
    },


    handleUploadSuccess(response) {
      if (response.code == "500") {
        this.$message({ message: '上传失败', type: 'error' })
      } else {
        console.log(response)
        this.uploadData.id = response.data.chengguoId
        this.fileParams.cgId = response.data.chengguoId
        this.getFileList()
      }
    },
    // 获取列表
    getFileList() {
      getFile(this.fileParams).then(response => {
        this.fileDataList = response.rows
        this.fileTotal = response.total
      })
    },

    handleDeleteFile(row) {
      console.log(row)
      removeFile({ fileId: row.fileId }).then(response => {
        this.$modal.msgSuccess('删除成功')
        this.getFileList()
      })
    },

    // 查看详情
    handleDetail(row) {
      this.reset();
      this.isShowDetail = true
      const chengguoId = row.chengguoId || this.ids
      this.uploadData.id = chengguoId.toString()
      this.fileParams.cgId = chengguoId.toString()
      this.getFileList()
      // if (this.issueState == 1) {
      //   this.$message.warning("已发布,不允许修改,请先撤销发布!");
      //   return false;
      // }
      getZhuanTiChengGuo(chengguoId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "专题成果详情";
      });
    }
  },
};
</script>
